//
//  CAViewController.m
//  testself
//
//  Created by Seimei on 12-10-22.
//  Copyright (c) 2012年 DEMO. All rights reserved.
//

#import "CAViewController.h"
#import "SensorsService.h"

float randomFloat(float Min, float Max){
    return ((arc4random()%RAND_MAX)/(RAND_MAX*1.0))*(Max-Min)+Min;
}

@interface CAViewController ()
{
    NSMutableArray *data4plot1;
    NSMutableArray *data4plot2;
    NSMutableArray *data4plot3;
}
@end

@implementation CAViewController
@synthesize rpmDash = _rpmDash,wenduDash = _wenduDash,speedDash = _speedDash,yaliDash = _yaliDash;
@synthesize chart = _chart;
@synthesize data4plot1,data4plot2,data4plot3;
@synthesize ave_acc=_ave_acc,ave_speed=_ave_speed,ave_ful=_ave_ful;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"主页", @"主页");
        //self.tabBarItem.image = [UIImage imageNamed:@"first"];

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    self.navigationItem.title = @"汽车王牌";
   
    UIImageView *im = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"rpm.png"]];
    [_rpmDash addSubview:im];
    [_rpmDash sendSubviewToBack:im];
    [im release];
    _rpmDash.minNumber = 0;
    _rpmDash.maxNumber = 8;
    _rpmDash.value = 1;
    
    UIImageView *im2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"speed.png"]];
    [_speedDash addSubview:im2];
    [_speedDash sendSubviewToBack:im2];
    [im2 release];
    _speedDash.minNumber = 0;
    _speedDash.maxNumber = 250;
    _speedDash.value = 10;
    
    
    UIImageView *im3 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"temp.png"]];
    [_wenduDash addSubview:im3];
    [_wenduDash sendSubviewToBack:im3];
    [im3 release];
    _wenduDash.minNumber = -40;
    _wenduDash.maxNumber = 220;
    _wenduDash.value = 60;
    
    UIImageView *im4 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yali.png"]];
    [_yaliDash addSubview:im4];
    [_yaliDash sendSubviewToBack:im4];
    [im4 release];
    _yaliDash.minNumber = 0;
    _yaliDash.maxNumber = 8;
    _yaliDash.value = 20;
    
    UIView *back = [[UIView alloc] initWithFrame:CGRectMake(0, 261, 320, 80)];
    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"chart.png"]];
    back.backgroundColor = background;
    [background release];
    back.alpha = 0.45;
        
    [self.view addSubview:back];
    
    
    //init chart
    [self chartInit];
    
    NSTimer *t = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(update) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
    
    
}

- (void)chartInit
{
    self.chart.dataSource = self;
    self.chart.delegate = self;
    self.chart.drawAxisX = NO;
    self.chart.drawAxisY = NO;
    self.chart.drawGridX = NO;
    self.chart.drawGridY = NO;
    
    self.chart.gridXColor = [UIColor whiteColor];
    self.chart.gridYColor = [UIColor whiteColor];
    
    //random init value for 3-plot
    self.data4plot1 = [NSMutableArray arrayWithCapacity:10];
    self.data4plot2 = [NSMutableArray arrayWithCapacity:10];
    self.data4plot3 = [NSMutableArray arrayWithCapacity:10];
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)update {
    _ave_speed.text = [NSString stringWithFormat:@"%@:%f",@"平均时速",[SensorsService avgVehicleSpeed]];
    _ave_ful.text = [NSString stringWithFormat:@"%@:%f",@"平均油耗",[SensorsService avgFuel]];
    _ave_acc.text = [NSString stringWithFormat:@"%@:%f",@"油门平均",[SensorsService avgAcceleratorPedalPosition]];
    
    //_speedDash.value = randomFloat(1 , 300);
    _speedDash.value = [SensorsService vehicleSpeed];
    
    if ([self.data4plot1 count] == 10) {
        [self.data4plot1 removeObjectAtIndex:0 ];
    }
    
    [self.data4plot1 addObject:[NSNumber numberWithFloat:randomFloat(1 , 300)]];
    
    //_yaliDash.value = randomFloat(1, 8);
    _yaliDash.value = [SensorsService map];
    
    [self.data4plot2 addObject:[NSNumber numberWithFloat:randomFloat(1, 8) + 150]];
    
    //_wenduDash.value = randomFloat(-40, 220);
    _wenduDash.value = [SensorsService intakeTemp];
    
    _rpmDash.value = [SensorsService engineRpm] / 1000 ;
    [self.data4plot3 addObject:[NSNumber numberWithFloat:randomFloat(50, 200) + 150]];
    
//    for (int i = 0; i < [self.data4plot1 count]; i++) {
//        printf("%f\n",[self.data4plot1 objectAtIndex:i]);
//    }
    
    [self.chart reloadData];
}

- (void)dealloc {
    [_rpmDash release];
    [_speedDash release];
    [_wenduDash release];
    [_yaliDash release];
    [_chart release];
    [_ave_speed release];
    [_ave_ful release];
    [_ave_acc release];
    [super dealloc];
}
- (IBAction)sinaSend:(id)sender {
    
    
    if (![[CHShareManager mainManager] sinaIsVailed]) {
        [[CHShareManager mainManager] showLoginOnViewController:self type:@"sina" finish:@selector(logInDidFinished:) failed:@selector(logInDidFailed:Error:)];
    }
    else{
        [[CHShareManager mainManager] sendWeibo:@"新浪微博一键分享" image:[self screenshot] type:@"sina" vc:self finish:@selector(sendDidFinished:) failed:@selector(sendDidError:)];
    }

}

- (IBAction)qqSend:(id)sender {
    if (![[CHShareManager mainManager] qqIsVailed]) {
        [[CHShareManager mainManager] showLoginOnViewController:self type:@"qq" finish:@selector(logInDidFinished:) failed:@selector(logInDidFailed:error:)];
    }
    else
    {
        [[CHShareManager mainManager] sendWeibo:@"腾讯尼玛一键分享" image:[self screenshot] type:@"qq" vc:self finish:@selector(sendDidFinished:) failed:@selector(sendDidError:)];//暂时不支持发送图片，可利用分享api传入image url来实现发送目的。
    }
    
}
#pragma mark - api delegate
- (void)logInDidFinished:(WBEngine *)_engine
{
    UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"登录成功" message:_engine.snsType delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
    [al show];
    [al release];
}

- (void)logInDidFailed:(WBEngine *)_engine error:(NSError *)_error
{
    
}

- (void)sendDidFinished:(id)_result
{
    NSLog(@"send did finished:%@",_result);
    UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"分享成功" message:nil delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
    [al show];
    [al release];
}

- (void)sendDidError:(NSError *)_error
{
    NSLog(@"%@",_error);
}



- (void)viewDidUnload {
    [self setChart:nil];
    [self setAve_speed:nil];
    [self setAve_ful:nil];
    [self setAve_acc:nil];
    [super viewDidUnload];
}

#pragma mark protocol S7GraphViewDataSource

- (NSUInteger)graphViewMaximumNumberOfXaxisValues:(S7GraphView *)graphView {
    return 10;
}

- (NSUInteger)graphViewNumberOfPlots:(S7GraphView *)graphView {
    /* Return the number of plots you are going to have in the view. 1+ */
    return 3;
}

- (NSArray *)graphViewXValues:(S7GraphView *)graphView {
    /* An array of objects that will be further formatted to be displayed on the X-axis.
     The number of elements should be equal to the number of points you have for every plot. */
    return [NSArray arrayWithObjects:[NSNumber numberWithInt:1],[NSNumber numberWithInt:2],[NSNumber numberWithInt:3],[NSNumber numberWithInt:4],[NSNumber numberWithInt:5],[NSNumber numberWithInt:6],[NSNumber numberWithInt:8],[NSNumber numberWithInt:9],[NSNumber numberWithInt:10], nil];
}

- (NSArray *)graphView:(S7GraphView *)graphView yValuesForPlot:(NSUInteger)plotIndex {
    /* Return the values for a specific graph. Each plot is meant to have equal number of points.
     And this amount should be equal to the amount of elements you return from graphViewXValues: method. */
    switch (plotIndex) {
        case 0:
            return self.data4plot1;
            break;
        case 1:
            return self.data4plot2;
            break;
        case 2:
            return self.data4plot3;
            break;
            
        default:
            break;
    }
}

- (BOOL)graphView:(S7GraphView *)graphView shouldFillPlot:(NSUInteger)plotIndex {
    return NO;
}

- (UIImage*)screenshot
{
    // Create a graphics context with the target size
    // On iOS 4 and later, use UIGraphicsBeginImageContextWithOptions to take the scale into consideration
    // On iOS prior to 4, fall back to use UIGraphicsBeginImageContext
    CGSize imageSize = [[UIScreen mainScreen] bounds].size;
    if (NULL != UIGraphicsBeginImageContextWithOptions)
        UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    else
        UIGraphicsBeginImageContext(imageSize);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // Iterate over every window from back to front
    for (UIWindow *window in [[UIApplication sharedApplication] windows])
    {
        if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen])
        {
            // -renderInContext: renders in the coordinate space of the layer,
            // so we must first apply the layer's geometry to the graphics context
            CGContextSaveGState(context);
            // Center the context around the window's anchor point
            CGContextTranslateCTM(context, [window center].x, [window center].y);
            // Apply the window's transform about the anchor point
            CGContextConcatCTM(context, [window transform]);
            // Offset by the portion of the bounds left of and above the anchor point
            CGContextTranslateCTM(context,
                                  -[window bounds].size.width * [[window layer] anchorPoint].x,
                                  -[window bounds].size.height * [[window layer] anchorPoint].y);
            
            // Render the layer hierarchy to the current context
            [[window layer] renderInContext:context];
            
            // Restore the context
            CGContextRestoreGState(context);
        }
    }
    
    // Retrieve the screenshot image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
}


@end
